package edu.pku.sei.modeler.figures.anchor;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PrecisionPoint;
import org.eclipse.draw2d.geometry.Rectangle;

import edu.pku.sei.modeler.model.common.BorderAnchor;

public class RectangleBorderAnchor extends BorderAnchor {

	public RectangleBorderAnchor(IFigure figure) {
		super(figure);
	}

	@Override
	public Point getBorderPoint(Point reference) {
		Rectangle rectangle = Rectangle.SINGLETON;
		rectangle.setBounds(getOwner().getBounds());
		getOwner().translateToAbsolute(rectangle);

		double dx = 0;
		double dy = 0;
		double tan = Math.atan2(rectangle.height, rectangle.width);
		if (angle >= -tan && angle <= tan) {
			dx = rectangle.width >> 1;
			dy = dx * Math.tan(angle);
		}
		else if (angle >= tan && angle <= Math.PI - tan) {
			dy = rectangle.height >> 1;
			dx = dy / Math.tan(angle);
		}
		else if (angle <= -tan && angle >= tan - Math.PI) {
			dy = - (rectangle.height >> 1);
			dx = dy / Math.tan(angle);
		}
		else {
			dx = -(rectangle.width >> 1);
			dy = dx * Math.tan(angle);
		}
		PrecisionPoint precisionPoint = new PrecisionPoint(rectangle.getCenter());
		precisionPoint.translate((int)dx, (int)dy);
//		System.out.println("border point: " + precisionPoint);
		return new Point(precisionPoint);
	}

}
